﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBL = DatabaseLayer;

namespace Speakup
{
    public static class ClassListThemeAssigner
    {
        static public void AssignTheme(Class speakupClass, int currentLevel)
        {
            AssignTheme(speakupClass, currentLevel, DBL.DatabaseContextFactory.Create());
        }

        static public void AssignTheme(Class speakupClass, int currentLevel, DBL.SpeakupEntities dbCtx)
        {
            int week = Week.GetWeek(speakupClass.ClassTime.Date);

            WeekTheme.ThemeFilter filter = WeekTheme.ByAllFilter(speakupClass.ClassName.Type, currentLevel, week);
            List<WeekTheme> themes = WeekTheme.GetWeekThemes(filter);

            if (themes.Count == 0)
            {
                speakupClass.Theme = null;
            }
            else
            {
                speakupClass.Theme = themes.First().Theme;
            }
        }

        static public void AssignThemes(ClassList classes, int currentLevel)
        {
            AssignThemes(classes, currentLevel, DBL.DatabaseContextFactory.Create());
        }

        static public void AssignThemes(ClassList classes, int currentLevel, DBL.SpeakupEntities dbCtx)
        {
            Dictionary<WeekThemeKey, List<Class>> themeKeyDict = new Dictionary<WeekThemeKey, List<Class>>();

            ThemeLevel defaultLevel = new ThemeLevel();
            
            foreach (Class c in classes)
            {
                int week = Week.GetWeek(c.ClassTime.Date);
                
                WeekThemeKey key = new WeekThemeKey(c.ClassName.Type, defaultLevel, week);

                if(!themeKeyDict.Keys.Contains(key))
                {
                    themeKeyDict[key] = new List<Class>();
                }

                themeKeyDict[key].Add(c);
                c.Theme = null;
            }

            WeekTheme.ThemeFilter filter = WeekTheme.LevelFilter(currentLevel);

            foreach (WeekTheme weekTheme in WeekTheme.GetWeekThemes(filter))
            {
                WeekThemeKey key = new WeekThemeKey(weekTheme.ClassType, defaultLevel, weekTheme.Week);

                if (themeKeyDict.Keys.Contains(key))
                {
                    foreach (Class c in themeKeyDict[key])
                    {
                        c.Theme = weekTheme.Theme;
                    }
                }
            }
        }

    }
}
